package myicesscheduler.web;

import myicesscheduler.hibernate.ReservationTypeTransaction;
import myicesscheduler.web.LectureCommand.TimeSlotCommand;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class LectureCommandValidator implements Validator
{
   protected final Log logger = LogFactory.getLog( getClass() );

   @SuppressWarnings( "unchecked" )
   public boolean supports( Class clazz )
   {
      return LectureCommand.class.equals( clazz );
   }

   public void validate( Object command, Errors err )
   {
      final LectureCommand cmd = (LectureCommand) command;
      if( null == cmd )
      {
         err.reject( "Null command object" );
         return;
      }
      logger.info( cmd.toString() );

      if( null == cmd.getSpeakerName() || cmd.getSpeakerName().equals( "" ) )
         err.rejectValue( "speakerName", "error.LectureCommandValidator.speakerName",
               "Speaker name is required" );

      if( null == cmd.getTopic() || cmd.getTopic().equals( "" ) )
         err.rejectValue( "topic", "error.LectureCommandValidator.topic", "Topic is required" );

      boolean bFoundLecture = false;
      for( final TimeSlotCommand timeSlotCmd : cmd.getTimeSlotCommands() )
      {
         if( false == timeSlotCmd.isEnabled() ) continue;
         if( timeSlotCmd.getReservationType() != ReservationTypeTransaction.getTypeId_lecture() )
            continue;
         bFoundLecture = true;
      }
      if( false == bFoundLecture )
         err.rejectValue( "timeSlotCommands", "error.LectureCommandValidator.timeSlotCommands",
               "At least one lecture must be assigned." );
   }
}
